package com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.entity.Project;
import com.entity.User;
import com.entity.UserProject;
import com.util.DBHelp;
import com.util.RowMapper;

public class UserProjectDao {

	private DBHelp<UserProject> db=new DBHelp<UserProject>();
	
	public UserProject findByProjectId(String projectId,String userId){
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT userid,te.username,te.password,projectid,tp.projectname,tp.projectcontent,tp.createtime,role FROM t_user_project AS tep ");
		sql.append("LEFT JOIN t_user AS te ON tep.userid = te.id ");
		sql.append("LEFT JOIN t_project AS tp ON tep.projectid = tp.id ");
		sql.append("where tep.projectid = ? and tep.userid = ?");
		return db.executeQueryForObject(sql.toString(), new UserProjectRowMapper(), projectId,userId);
	}
	public void save(UserProject up) {
		String sql  = "insert into t_user_project(userid,projectid,role) values(?,?,?)";
		db.executeSQL(sql,up.getUserid(),up.getProjectid(),up.getRole());
	}
	
	
	private class UserProjectRowMapper implements RowMapper<UserProject>{

		public UserProject mapRow(ResultSet rs) throws SQLException {
			// TODO Auto-generated method stub
			UserProject up=new UserProject();
			up.setRole(rs.getString("role"));
			User u=new User();
			u.setId(rs.getString("userid"));
			u.setPassword(rs.getString("password"));
			u.setUsername(rs.getString("username"));
			up.setUser(u);
			up.setUserid(rs.getString("userid"));
			
			Project p=new Project();
			p.setCreateTime(rs.getString("createtime"));
			p.setProjectContent(rs.getString("projectcontent"));
			p.setProjectName(rs.getString("projectname"));
			up.setProject(p);
			up.setProjectid(rs.getString("projectid"));
			
			return up;
		}
		
		
	}
	
	
	
}
